const http = require('http');
const resolveUrl = require('url');
const path = require('path')
const fs = require('fs');
const PORT = 9999;

const MIME = {
  "html": "text/html",
  "js": "text/javascript",
  "css": "text/css",
  "jpg": "image/jpeg",
  "ico": "image/x-icon"
}

const server = http.createServer((req, res) => {

  // 1. 读文件
  // 后缀  .html  .js  .css
  const url = req.url;
  const pathname = resolveUrl.parse(url).pathname;
  const extname = path.extname(pathname);

  const contentype = MIME[extname.slice(1)] || 'text/plain'
  const filePath = path.join(__dirname, 'public', pathname)
  console.log(filePath, 'filePath')

  if (extname) {
    if (extname === '.ico') {
      res.end('111')
      return;
    }
    // 响应头
    res.writeHead(200, {
      "content-type": `${contentype};charset=UTF-8`
    });
    //建立流对象，读文件
    var stream = fs.createReadStream(filePath);
    //读取文件
    stream.pipe(res);
    return;
  } else {
    res.writeHead(200, {
      'Content-type': "text/json"
    })
    // 2. 写接口
    // api/login  api/register
    res.end('接口')
    return;
  }
})

server.listen(PORT, () => {
  console.log(`server port is ${PORT}`)
})